<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Order extends UserCommonController
{
    private $number_perpage;
    function __construct()
    {
        parent::__construct();
        $this->number_perpage = 10;
        $this->load->model('MOrder');
    }

    public function index(){
        $list = $this->MOrder->getList($this->param,$this->user->id,$this->number_perpage);
        if(count($list)){
            $this->ReturnJson(200,true,'获取成功',$list);
        }else{
            $this->ReturnJson(3001,false,'暂无订单数据');
        }
    }

    public function add(){
        $this->load->model('MUser');
        // 验证是否有未还车辆
        $exist = $this->MOrder->getOne(['user_id' => $this->user->id, 'pay_status' => '<> 0']);
        if ($exist){
            $this->ReturnJson(3002,false,'当前有未结算完成订单，不可继续扫码用车！',$exist);
        }
        if (!$this->user->user_type){
            $this->ReturnJson(1003,false,'您已被平台拉黑，不可扫码用车，请联系管理员处理！',$this->user);
        }
        $obj = $this->MOrder->createVo();
        $this->load->helper('populate');
        $newObj = populate((Object)((Array)$obj), $this->param);
        if ($this->param['user_id'] !== $this->user->id){
            $this->ReturnJson(1007,false,'非法操作');
        }
        $oid = $this->MOrder->add($newObj);
        if($oid){
            $this->db->update('car',['last_return_time' => 0,'status' => 1],['id' => $this->param['car_id']]);
            $this->ReturnJson(200,true,'添加成功',$oid);
        }else{
            $this->ReturnJson(3001,false,'下单失败，请稍后重试');
        }
    }

    public function detail(){
        $order = $this->MOrder->getApiDetail($this->param['oid']);
        $end = $order->return_time?$order->return_time:time();
        $order->used_time = $end - $order->create_time;
        if ($order){
            $this->ReturnJson(200,true,'获取成功',$order,$this->param);
        }else{
            $this->ReturnJson(404,false,'未找到该订单');
        }
    }

    public function return_car(){
        $order = $this->MOrder->getById($this->param['oid']);
        $order->status = 1;
        $order->return_time = time();
        $order->amount = number_format((ceil((time() - $order->create_time)/(3600*24))) * $order->price,2);
        if ($this->MOrder->update($order)){
            $data = $this->MOrder->getApiDetail($this->param['oid']);
            $this->ReturnJson(200,true,'申请成功',$data);
        }else{
            $this->ReturnJson(500,false,'操作失败，请稍后重试',$order);
        }
    }
}
